package dbinit;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.address.model.continent.Continent;
import core.address.model.country.Country;
import core.address.model.region.Region;
import core.address.model.state.State;
import core.util.HibernateCoreUtil;

public class InitRegion 
{
	public static Region getRegionByUuid(Long uuid)
	{
		Region r = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				r = (Region) session.get(Region.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return r ;
	}
	public static Region getRegionByName(String name)
	{
		Region r = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			r = (Region)session.createCriteria(Region.class).add(Restrictions.eq("name", name)).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return r ;
	}
	public static Long doinit(String name , State state , Country country ,Continent continent)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Long uuid = null;
		Region r = getRegionByName(name);
		try
		{
			transaction = session.beginTransaction();
			if(r == null)
			{
				r = new Region();
				r.setName(name);
				r.setContinent(continent);
				r.setCountry(country);
				r.setState(state);
				r = (Region) session.merge(r);
				uuid = r.getUuid();
			}
			else
			{
				r.setContinent(continent);
				r.setCountry(country);
				r.setState(state);
				session.merge(r);
				uuid = r.getUuid();
			}
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return uuid ;
	}
}
